package i18n

import (
	"fmt"
	"strings"
)

// simple in-memory dictionary based i18n
var (
	lang = "zh-CN"

	translations = map[string]map[string]string{
		"zh-CN": {
			"category.video": "视频",
			"category.music": "音乐",
			"category.archive": "压缩",
			"category.image": "图片",
			"category.document": "文档",
			"category.program": "程序",
			"category.image_iso": "镜像",

			"action.quick_add.title": "快速添加",
			"action.quick_add.ok": "添加",
			"action.ok": "确定",
			"action.cancel": "取消",

			"field.url":            "URL",
			"field.filename":       "文件名",
			"field.priority":       "优先级",
			"field.mirrors":        "镜像 URL（可选）",
			"field.checksum_algo":  "校验算法（可选）",
			"field.checksum_value": "校验值（hex）",

			"priority.high": "高",
			"priority.medium": "中",
			"priority.low": "低",

			"add.title": "添加下载",
			"add.url.placeholder": "输入下载 URL",
			"add.filename.placeholder": "保存文件名（可选）",
			"add.sources.placeholder": "每行一个镜像 URL（可留空）",
			"add.checksum.placeholder": "留空表示不校验",

			"header.name": "名称",
			"header.status": "状态",
			"header.progress": "进度",
			"header.speed": "速度",
			"header.priority": "优先级",
			"header.time": "时间",

			"status.ready": "就绪",

			"speed.title": "设置速度上限 (MB/s)",
			"speed.apply": "应用",
			"speed.cancel": "取消",
			"speed.field.placeholder": "MB/s（留空为不限）",
			"error.speed.invalid": "请输入不小于 0 的数字，或留空表示不限",
			"error.config.save": "保存配置失败: %v",

			// window & menus
			"app.title": "下载管理器",
			"menu.file": "文件",
			"menu.edit": "编辑",
			"menu.add": "添加下载",
			"menu.import": "导入任务...",
			"menu.export": "导出任务...",
			"menu.start_all": "开始全部",
			"menu.pause_all": "暂停全部",
			"menu.clear_completed": "清除已完成",
			"menu.quit": "退出",

			// filters and sorting
			"filter.search.placeholder": "搜索 名称/URL",
			"filter.status.all": "全部",
			"filter.status.running": "运行",
			"filter.status.waiting": "等待",
			"filter.status.paused": "暂停",
			"filter.status.completed": "完成",
			"filter.status.failed": "失败",
			"filter.category.all": "全部",
			"filter.category.video": "视频",
			"filter.category.music": "音乐",
			"filter.category.archive": "压缩",
			"filter.category.iso": "镜像",
			"filter.category.program": "程序",
			"filter.category.document": "文档",
			"filter.category.image": "图片",
			"sort.time.new_first": "时间(新→旧)",
			"sort.time.old_first": "时间(旧→新)",
			"sort.priority": "优先级",
			"sort.name": "名称",
			"sort.status": "状态",

			// bottom bar
			"button.speed": "限速...",

			// close notification
			"notify.bg.title": "仍在后台运行",
			"notify.bg.content": "下载任务继续执行。要退出请在“文件→退出”中选择。",

			// tray
			"tray.title": "下载管理器",
			"tray.status.ready": "状态: 就绪",
			"tray.open_window": "打开主窗口",
			"tray.quit": "退出",
			"tray.speed": "限速",
			"tray.batch": "批量",
			"tray.batch.start_all": "全部开始",
			"tray.batch.pause_all": "全部暂停",
			"tray.clear_completed": "清除已完成",
			"tray.autoshutdown.on": "自动关机: 开",
			"tray.autoshutdown.off": "自动关机: 关",
			"tray.cancel_shutdown": "取消关机",
			"tray.clip.on": "剪贴板监控: 开",
			"tray.clip.off": "剪贴板监控: 关",
			"tray.api.on": "浏览器接口: 开",
			"tray.api.off": "浏览器接口: 关",
			"tray.status.fmt": "状态: 运行:%d 等待:%d 完成:%d | %.2f MB/s",

			// shutdown notifications
			"notify.shutdown.armed.title": "将自动关机",
			"notify.shutdown.armed.content": "%d 分钟后自动关机（托盘可取消）",
			"notify.shutdown.canceled.title": "已取消关机",
			"notify.shutdown.canceled.content": "自动关机已取消",

			// speed status text
			"status.speed.limit": "限速: %s",
			"status.speed.unlimited": "不限",

			// more actions dialog
			"more.title": "更多",
			"more.apply": "应用",
			"more.cancel": "取消",
			"label.modify_priority": "修改优先级",

			// settings dialog
			"settings.title": "设置",
			"field.language": "语言",
			"settings.apply": "应用",
			"settings.cancel": "取消",
			"settings.hint.restart": "部分文本需要重启后完全生效",
			"settings.rules_json": "规则(JSON)",
			"settings.group_limits_json": "分组并发(JSON)",
			"error.json.invalid": "JSON 格式不正确",

			// downloader settings fields
			"field.chunks": "分段数",
			"field.max_retries": "最大重试",
			"field.retry_backoff": "退避秒",

			// validation errors
			"error.int.invalid": "请输入有效整数",
			"error.chunks.min1": "分段数必须≥1",
			"error.int.nonneg": "请输入不小于 0 的整数",
			"error.checksum.format": "请输入合法的十六进制校验值",

			// task status rendering
			"status.scheduled.at": "已计划 %s",
			"status.waiting": "等待",
			"status.running.known": "下载中 %.1f%% %.1f/%.1f MB %.1f MB/s %s",
			"status.running.unknown": "下载中 ?? MB / ?? MB %.1f MB/s",
			"status.paused": "已暂停",
			"status.completed": "完成",
			"status.failed": "失败: %v",
			"status.unknown": "未知",
			"status.source": "来源: %s",
			"details.current_source": "当前来源",
			"details.parts_completed": "已完成分段",
			"details.retries": "重试次数",
			"details.failed_parts": "未完成分段",
			"details.sources": "所有来源",
			"details.title": "任务详情",
			"details.close": "关闭",

			// remove task confirm
			"confirm.remove.title": "删除任务",
			"confirm.remove.message": "确定删除任务并移除列表？\n%s",
			"confirm.ok": "确定",
			"confirm.cancel": "取消",

			// http api errors (localized message)
			"error.api.unauthorized": "未授权",
			"error.api.missing_url": "缺少 URL",

			// context menu
			"context.start": "开始",
			"context.pause": "暂停",
			"context.prio_up": "提高优先级",
			"context.prio_down": "降低优先级",
			"context.open_file": "打开文件",
			"context.open_dir": "打开所在目录",
			"context.schedule": "设置开始时间...",
			"context.delete": "删除",
			"context.title": "操作",
			"context.close": "关闭",
			"context.apply_rules": "应用规则",

			// schedule dialog
			"schedule.title": "设置开始时间",
			"schedule.apply": "应用",
			"schedule.cancel": "取消",
			"schedule.field.placeholder": "YYYY-MM-DD HH:MM（留空清除）",
			"error.schedule.format": "时间格式应为 YYYY-MM-DD HH:MM",

			// batch add
			"batch.title": "批量添加",
			"batch.add": "添加",
			"batch.cancel": "取消",
			"batch.url.placeholder": "每行一个 URL",
			"field.url_list": "URL 列表",
		},
		"en-US": {
			"category.video": "Video",
			"category.music": "Music",
			"category.archive": "Archive",
			"category.image": "Image",
			"category.document": "Document",
			"category.program": "Program",
			"category.image_iso": "Image",

			"action.quick_add.title": "Quick Add",
			"action.quick_add.ok": "Add",
			"action.ok": "OK",
			"action.cancel": "Cancel",

			"field.url":        "URL",
			"field.filename":   "Filename",
			"field.priority":   "Priority",
			"field.mirrors":    "Mirror URLs (optional)",
			"field.checksum_algo":  "Checksum Algorithm (optional)",
			"field.checksum_value": "Checksum (hex)",
			"field.start_time": "Start Time",

			"priority.high": "High",
			"priority.medium": "Medium",
			"priority.low": "Low",

			"add.title": "Add Download",
			"add.url.placeholder": "Enter download URL",
			"add.filename.placeholder": "Save filename (optional)",
			"add.sources.placeholder": "One mirror URL per line (optional)",
			"add.checksum.placeholder": "Leave empty to skip verification",

			"header.name": "Name",
			"header.status": "Status",
			"header.progress": "Progress",
			"header.speed": "Speed",
			"header.priority": "Priority",
			"header.time": "Time",

			"status.ready": "Ready",

			"speed.title": "Set Speed Limit (MB/s)",
			"speed.apply": "Apply",
			"speed.cancel": "Cancel",
			"speed.field.placeholder": "MB/s (leave empty for unlimited)",
			"error.speed.invalid": "Please enter a number >= 0, or leave empty for unlimited",
			"error.config.save": "Failed to save config: %v",

			// window & menus
			"app.title": "Download Manager",
			"menu.file": "File",
			"menu.edit": "Edit",
			"menu.add": "Add Download",
			"menu.import": "Import Tasks...",
			"menu.export": "Export Tasks...",
			"menu.start_all": "Start All",
			"menu.pause_all": "Pause All",
			"menu.clear_completed": "Clear Completed",
			"menu.quit": "Quit",

			// filters and sorting
			"filter.search.placeholder": "Search Name/URL",
			"filter.status.all": "All",
			"filter.status.running": "Running",
			"filter.status.waiting": "Waiting",
			"filter.status.paused": "Paused",
			"filter.status.completed": "Completed",
			"filter.status.failed": "Failed",
			"filter.category.all": "All",
			"filter.category.video": "Video",
			"filter.category.music": "Music",
			"filter.category.archive": "Archive",
			"filter.category.iso": "ISO",
			"filter.category.program": "Program",
			"filter.category.document": "Document",
			"filter.category.image": "Image",
			"sort.time.new_first": "Time (new→old)",
			"sort.time.old_first": "Time (old→new)",
			"sort.priority": "Priority",
			"sort.name": "Name",
			"sort.status": "Status",

			// bottom bar
			"button.speed": "Speed...",

			// close notification
			"notify.bg.title": "Still running in background",
			"notify.bg.content": "Downloads continue. To quit, choose File → Quit.",

			// tray
			"tray.title": "Download Manager",
			"tray.status.ready": "Status: Ready",
			"tray.open_window": "Open Main Window",
			"tray.quit": "Quit",
			"tray.speed": "Speed",
			"tray.batch": "Batch",
			"tray.batch.start_all": "Start All",
			"tray.batch.pause_all": "Pause All",
			"tray.clear_completed": "Clear Completed",
			"tray.autoshutdown.on": "Auto Shutdown: On",
			"tray.autoshutdown.off": "Auto Shutdown: Off",
			"tray.cancel_shutdown": "Cancel Shutdown",
			"tray.clip.on": "Clipboard Monitor: On",
			"tray.clip.off": "Clipboard Monitor: Off",
			"tray.api.on": "Browser API: On",
			"tray.api.off": "Browser API: Off",
			"tray.status.fmt": "Status: Running:%d Waiting:%d Completed:%d | %.2f MB/s",

			// shutdown notifications
			"notify.shutdown.armed.title": "Auto shutdown scheduled",
			"notify.shutdown.armed.content": "Will shutdown in %d minutes (cancel from tray)",
			"notify.shutdown.canceled.title": "Shutdown canceled",
			"notify.shutdown.canceled.content": "Auto shutdown has been canceled",

			// speed status text
			"status.speed.limit": "Speed: %s",
			"status.speed.unlimited": "Unlimited",

			// more actions dialog
			"more.title": "More",
			"more.apply": "Apply",
			"more.cancel": "Cancel",
			"label.modify_priority": "Modify Priority",

			// settings dialog
			"settings.title": "Settings",
			"field.language": "Language",
			"settings.apply": "Apply",
			"settings.cancel": "Cancel",
			"settings.hint.restart": "Some texts require restart to fully apply",
			"settings.rules_json": "Rules (JSON)",
			"settings.group_limits_json": "Group Limits (JSON)",
			"error.json.invalid": "Invalid JSON format",

			// downloader settings fields
			"field.chunks": "Chunks",
			"field.max_retries": "Max Retries",
			"field.retry_backoff": "Retry Backoff (sec)",

			// validation errors
			"error.int.invalid": "Please enter a valid integer",
			"error.chunks.min1": "Chunks must be ≥ 1",
			"error.int.nonneg": "Please enter an integer ≥ 0",
			"error.checksum.format": "Please enter a valid hex checksum",

			// task status rendering
			"status.scheduled.at": "Scheduled %s",
			"status.waiting": "Waiting",
			"status.running.known": "Downloading %.1f%% %.1f/%.1f MB %.1f MB/s %s",
			"status.running.unknown": "Downloading ?? MB / ?? MB %.1f MB/s",
			"status.paused": "Paused",
			"status.completed": "Completed",
			"status.failed": "Failed: %v",
			"status.unknown": "Unknown",
			"status.source": "Source: %s",
			"details.current_source": "Current Source",
			"details.parts_completed": "Parts Completed",
			"details.retries": "Retries",
			"details.failed_parts": "Incomplete Parts",
			"details.sources": "All Sources",
			"details.title": "Task Details",
			"details.close": "Close",

			// remove task confirm
			"confirm.remove.title": "Remove Task",
			"confirm.remove.message": "Are you sure to remove this task from the list?\n%s",
			"confirm.ok": "OK",
			"confirm.cancel": "Cancel",

			// http api errors (localized message)
			"error.api.unauthorized": "Unauthorized",
			"error.api.missing_url": "Missing URL",

			// context menu
			"context.start": "Start",
			"context.pause": "Pause",
			"context.prio_up": "Increase Priority",
			"context.prio_down": "Decrease Priority",
			"context.open_file": "Open File",
			"context.open_dir": "Open Folder",
			"context.schedule": "Schedule Start...",
			"context.delete": "Delete",
			"context.title": "Actions",
			"context.close": "Close",
			"context.apply_rules": "Apply Rules",

			// schedule dialog
			"schedule.title": "Schedule Start",
			"schedule.apply": "Apply",
			"schedule.cancel": "Cancel",
			"schedule.field.placeholder": "YYYY-MM-DD HH:MM (empty to clear)",
			"error.schedule.format": "Time format should be YYYY-MM-DD HH:MM",

			// batch add
			"batch.title": "Batch Add",
			"batch.add": "Add",
			"batch.cancel": "Cancel",
			"batch.url.placeholder": "One URL per line",
			"field.url_list": "URL List",
		},
	}
)

// SetLanguage sets current language, fallback to zh-CN if unknown.
func SetLanguage(code string) {
	code = strings.TrimSpace(code)
	if _, ok := translations[code]; ok {
		lang = code
		return
	}
	// normalize like zh_CN -> zh-CN
	code = strings.ReplaceAll(code, "_", "-")
	if _, ok := translations[code]; ok {
		lang = code
		return
	}
	lang = "zh-CN"
}

// T returns translation for key in current language, if not found returns the key.
func T(key string) string {
	if m, ok := translations[lang]; ok {
		if v, ok2 := m[key]; ok2 {
			return v
		}
	}
	return key
}

// TF formats a translation with fmt.Sprintf semantics.
func TF(key string, args ...any) string {
	return fmt.Sprintf(T(key), args...)
}
